package servlets;

import java.io.IOException;
import java.util.ArrayList;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import managers.DeviceManager;
import entities.DeviceNC;
import fileServices.WebFileService;

/**
 * Servlet implementation class FileTransferServlet
 */
@WebServlet("/FileTransfer")
public class FileTransferServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	@EJB
	DeviceManager dm;
    public FileTransferServlet() {
        super();
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String fileName = request.getParameter("hostF");
		boolean isHost = true;
		if(fileName == null){
			fileName = request.getParameter("targetF");
			isHost = false;
		}
		
		String hostIp = request.getParameter("hostIp");
		String targetIp = request.getParameter("targetIp");		
		
		WebFileService wfs = new WebFileService();
		wfs.TransferFile(hostIp, targetIp, fileName);


		ArrayList<String> targetFiles = wfs.getFileNames(targetIp);
		ArrayList<String> hostFiles = wfs.getFileNames(hostIp);
		DeviceNC host = dm.getDevice(request.getParameter("hostUUID"), false);
		DeviceNC target = dm.getDevice(request.getParameter("targetUUID"), false);
		
		if(isHost){
			request.setAttribute("targetFiles", targetFiles);			
			request.setAttribute("hostFiles", hostFiles);			
			request.setAttribute("host", host);			
			request.setAttribute("target", target);
		}else{
			request.setAttribute("hostFiles", targetFiles);
			request.setAttribute("targetFiles", hostFiles);
			request.setAttribute("host", target);
			request.setAttribute("target", host);
		}
		
		request.getRequestDispatcher("WEB-INF/DeviceOverview.jsp").forward(request, response);
	}

}
